package usefunction;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * @author: fqtang
 * @date: 2024/10/07/22:53
 * @description: 使用函数式接口练习
 */
public class Exercise3 {

	public static void main(String[] args) {
		//传入的函数对象筛选出偶数
		List<Integer> filter = filter(List.of(1, 2, 3, 4, 5, 6, 7), i -> (i & 1) == 0);
		filter.forEach(System.out::println);
		System.out.println("------------");

		//把整型转换成字符串逻辑提出来成函数对象传入函数式接口
		List<String> map = map(List.of(1, 2, 3, 4, 5, 6, 7), (Integer number) -> String.valueOf(number));
		map.forEach(System.out::println);
		System.out.println("------------");

		//consume(List.of( 4, 5, 6, 7), System.out::println);

		List<Integer> supply = supply(3, () -> ThreadLocalRandom.current()
			.nextInt());
		System.out.println(supply);
	}

	static List<Integer> filter(List<Integer> sourceList, Predicate<Integer> predicate) {
		List<Integer> targetList = new ArrayList<>();
		for(Integer i : sourceList) {
			if(predicate.test(i)) {
				targetList.add(i);
			}
		}

		return targetList;
	}

	static List<String> map(List<Integer> sourceList, Function<Integer, String> changer) {
		List<String> targetList = new ArrayList<>();
		for(Integer i : sourceList) {
			targetList.add(changer.apply(i));
		}

		return targetList;
	}

	static void consume(List<Integer> sourceList, Consumer<Integer> consumer) {
		for(Integer i : sourceList) {
			consumer.accept(i);
		}
	}

	static List<Integer> supply(int count, Supplier<Integer> supplier) {
		List<Integer> targetList = new ArrayList<>();
		for(int i=0;i<count;i++) {
			targetList.add(supplier.get());
		}

		return targetList;
	}

}
